local FSM = Class()

local stateList = {}
local currentState = nil

function FSM:add(state)
    local key = state:getKey()

    if key == nil then
        Debug.Log("key cannot be nil")
        return
    end

    if stateList[key] ~= nil then
        Debug.Log("A state with same key" .. key .. 'already exist')
        return
    end

    if nil ~= state then
        stateList[key] = state
    end
end

function FSM:getState(key)
    local s = nil
    if key ~= nil then
        s = stateList[key]
    end
    return s
end

function FSM:transformToState(state)
    if state == nil then return end

    if state.key == nil then return end

    if stateList[state:getKey()] == nil then
        Debug.Log("Use FSM:add() to add state to FSM first.")
        return
    end

    if currentState ~= nil then
        currentState:exit()
    end

    currentState = state

    if (currentState ~= nil) then
        currentState:enter()
    end
end

function FSM:update()
    if currentState ~= nil then
        currentState:update()
    end
end

function FSM:exit()
    if currentState ~= nil then
        currentState.exit()
    end

    for k in pairs (stateList) do
        stateList[k] = nil
    end
end

return FSM